﻿using System.Collections.Generic;
using System.Text;

namespace PropertyExpression.QueryExecutor.Test
{
    public static class ProductFacade
    {
        public static IEnumerable<ProductProjection> SearchProducts(string productNumber, string name)
        {
            return QueryExecutor.Execute<ProductProjection>(
                context =>
                    {
                        var nameLocalizedColumnName = Localization.GetLocalizedColumnName("Name", "ru-RU");

                        context.Builder.AppendFormat(
 @"SELECT TOP 10 
    ProductNumber, 
    {0} AS Name
FROM 
    Production.Product 
",
                            nameLocalizedColumnName);

                        var whereBuilder = new StringBuilder();

                        if (!string.IsNullOrEmpty(productNumber))
                        {
                            whereBuilder.Append("ProductNumber = @ProductNumber");
                            context.AddParameter("@ProductNumber", productNumber);
                        }

                        if (!string.IsNullOrEmpty(name))
                        {
                            StringBuilderExtensions.AppendIfNotEmpty(whereBuilder, " OR ")
                                .AppendFormat("{0} LIKE @Name", nameLocalizedColumnName);
                            context.AddParameter("@Name", name);
                        }

                        if (whereBuilder.Length != 0)
                            context.Builder.AppendFormat(
@"
WHERE
    {0}",
                                whereBuilder);
                    }
                );
        }
    }

    public class ProductProjection
    {
        public string ProductNumber { get; set; }
        public string Name { get; set; }
    }
}